<template>
  <div class="folder-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="header-left">
          <div class="header-icon">
            <el-icon><FolderOpened /></el-icon>
          </div>
          <div class="header-text">
            <h2>文件夹管理</h2>
            <p>管理您的所有文件夹，组织文件结构</p>
          </div>
        </div>

        <div class="header-actions">
          <el-button type="primary" @click="$router.push('/new')">
            <el-icon><Plus /></el-icon>
            新建文件夹
          </el-button>
          <el-button @click="refreshFolders">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-section">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon folders">
                <el-icon><Folder /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ state.length }}</div>
                <div class="stats-label">文件夹总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon recent">
                <el-icon><Clock /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ recentCount }}</div>
                <div class="stats-label">本周新建</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="8">
          <el-card class="stats-card">
            <div class="stats-content">
              <div class="stats-icon storage">
                <el-icon><Files /></el-icon>
              </div>
              <div class="stats-info">
                <div class="stats-number">{{ totalFiles }}</div>
                <div class="stats-label">包含文件</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索文件夹名称..."
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="12">
          <div class="view-controls">
            <el-radio-group v-model="viewMode" @change="handleViewChange">
              <el-radio-button label="grid">
                <el-icon><Grid /></el-icon>
                网格视图
              </el-radio-button>
              <el-radio-button label="list">
                <el-icon><List /></el-icon>
                列表视图
              </el-radio-button>
            </el-radio-group>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 文件夹内容 -->
    <div class="folders-content">
      <!-- 网格视图 -->
      <div v-if="viewMode === 'grid'" class="grid-view">
        <div v-if="filteredFolders.length === 0" class="empty-state">
          <el-empty description="暂无文件夹">
            <el-button type="primary" @click="$router.push('/new')">
              创建第一个文件夹
            </el-button>
          </el-empty>
        </div>

        <div v-else class="folder-grid">
          <div
            v-for="folder in filteredFolders"
            :key="folder.id"
            class="folder-card"
            @click="openFolder(folder)"
          >
            <div class="folder-icon">
              <el-icon><Folder /></el-icon>
            </div>

            <div class="folder-info">
              <div class="folder-name" :title="folder.folder_name">
                {{ folder.folder_name }}
              </div>
              <div class="folder-meta">
                <span class="folder-date">{{ formatDate(folder.created_at) }}</span>
              </div>
            </div>

            <div class="folder-actions" @click.stop>
              <el-dropdown trigger="click">
                <el-button type="text" class="action-btn">
                  <el-icon><MoreFilled /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="openFolder(folder)">
                      <el-icon><View /></el-icon>
                      查看文件
                    </el-dropdown-item>
                    <el-dropdown-item @click="renameFolder(folder)">
                      <el-icon><Edit /></el-icon>
                      重命名
                    </el-dropdown-item>
                    <el-dropdown-item @click="deleteFolder(folder.id)" divided>
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </div>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-else class="list-view">
        <el-table
          :data="filteredFolders"
          style="width: 100%"
          v-loading="loading"
          @row-click="openFolder"
        >
          <el-table-column label="文件夹名称" min-width="200">
            <template #default="{ row }">
              <div class="folder-cell">
                <el-icon class="folder-icon-small"><Folder /></el-icon>
                <span class="folder-name">{{ row.folder_name }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatDateTime(row.created_at) }}
            </template>
          </el-table-column>

          <el-table-column label="文件数量" width="120">
            <template #default="{ row }">
              <el-tag size="small">{{ row.fileCount || 0 }} 个文件</el-tag>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="200" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" size="small" @click.stop="openFolder(row)">
                查看
              </el-button>
              <el-button size="small" @click.stop="renameFolder(row)">
                重命名
              </el-button>
              <el-button type="danger" size="small" @click.stop="deleteFolder(row.id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 重命名对话框 -->
    <el-dialog
      v-model="renameDialogVisible"
      title="重命名文件夹"
      width="400px"
    >
      <el-form :model="renameForm" :rules="renameRules" ref="renameFormRef">
        <el-form-item label="新名称" prop="newName">
          <el-input
            v-model="renameForm.newName"
            placeholder="请输入新的文件夹名称"
            maxlength="50"
            show-word-limit
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="renameDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRename" :loading="renameLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import {
  FolderOpened,
  Plus,
  Refresh,
  Folder,
  Clock,
  Files,
  Search,
  Grid,
  List,
  MoreFilled,
  View,
  Edit,
  Delete
} from "@element-plus/icons-vue";
import { getFolderApi, deleteFolderApi, renameFolderApi } from "@/utils/api";

const router = useRouter();

// 响应式数据
const state = ref([]);
const loading = ref(false);
const searchKeyword = ref("");
const viewMode = ref("grid");
const renameDialogVisible = ref(false);
const renameLoading = ref(false);
const renameFormRef = ref();

const renameForm = ref({
  newName: "",
  folderId: null
});

const renameRules = {
  newName: [
    { required: true, message: "请输入文件夹名称", trigger: "blur" },
    { min: 1, max: 50, message: "文件夹名称长度在 1 到 50 个字符", trigger: "blur" },
    {
      pattern: /^[^<>:"/\\|?*]+$/,
      message: "文件夹名称不能包含特殊字符 < > : \" / \\ | ? *",
      trigger: "blur"
    }
  ]
};

// 计算属性
const filteredFolders = computed(() => {
  if (!searchKeyword.value) return state.value;
  return state.value.filter(folder =>
    folder.folder_name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});

const recentCount = computed(() => {
  const oneWeekAgo = new Date();
  oneWeekAgo.setDate(oneWeekAgo.getDate() - 7);

  return state.value.filter(folder =>
    new Date(folder.created_at) > oneWeekAgo
  ).length;
});

const totalFiles = computed(() => {
  return state.value.reduce((total, folder) => total + (folder.fileCount || 0), 0);
});

// 方法
const getFolders = async () => {
  loading.value = true;
  try {
    const id = localStorage.getItem("id");
    const response = await getFolderApi({ id });
    if (response.code === 200) {
      state.value = response.data.data.map((item) => ({
        ...item,
        created_at: item.created_at.split("T")[0],
        fileCount: Math.floor(Math.random() * 20) // 模拟文件数量，实际应该从API获取
      }));
    }
  } catch (error) {
    console.error("Error fetching folders:", error);
    ElMessage.error("加载文件夹失败");
  } finally {
    loading.value = false;
  }
};

const refreshFolders = () => {
  getFolders();
  ElMessage.success("已刷新文件夹列表");
};

const deleteFolder = async (id) => {
  try {
    await ElMessageBox.confirm(
      "删除文件夹将同时删除其中的所有文件，此操作不可恢复。确定要删除吗？",
      "确认删除",
      {
        confirmButtonText: "确定删除",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    const response = await deleteFolderApi({ id });
    if (response.code === 200) {
      ElMessage.success("文件夹删除成功");
      await getFolders();
    } else {
      ElMessage.error(response.msg || "删除失败");
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error("Error deleting folder:", error);
      ElMessage.error("删除失败，请重试");
    }
  }
};

const openFolder = (folder) => {
  router.push(`/details/${folder.id}`);
};

const renameFolder = (folder) => {
  renameForm.value = {
    newName: folder.folder_name,
    folderId: folder.id
  };
  renameDialogVisible.value = true;
};

const confirmRename = async () => {
  if (!renameFormRef.value) return;

  try {
    const valid = await renameFormRef.value.validate();
    if (!valid) return;

    renameLoading.value = true;

    const response = await renameFolderApi({
      id: renameForm.value.folderId,
      folder_name: renameForm.value.newName
    });

    if (response.code === 200) {
      ElMessage.success("重命名成功");
      renameDialogVisible.value = false;
      await getFolders();
    } else {
      ElMessage.error(response.msg || "重命名失败");
    }
  } catch (error) {
    console.error("重命名失败:", error);
    ElMessage.error("重命名失败，请重试");
  } finally {
    renameLoading.value = false;
  }
};

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
};

const handleViewChange = (mode) => {
  ElMessage.info(`已切换到${mode === 'grid' ? '网格' : '列表'}视图`);
};

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString('zh-CN');
};

const formatDateTime = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN');
};

// 生命周期
onMounted(() => {
  getFolders();
});
</script>

<style lang="less" scoped>
.folder-management {
  padding: 20px;
}

.page-header {
  margin-bottom: 24px;

  .header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      display: flex;
      align-items: center;
      gap: 16px;

      .header-icon {
        width: 50px;
        height: 50px;
        background: linear-gradient(135deg, #409eff, #67c23a);
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        color: white;
        font-size: 20px;
      }

      .header-text {
        h2 {
          margin: 0 0 4px 0;
          color: #303133;
          font-size: 20px;
          font-weight: 600;
        }

        p {
          margin: 0;
          color: #606266;
          font-size: 14px;
        }
      }
    }

    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
}

.stats-section {
  margin-bottom: 24px;

  .stats-card {
    border-radius: 8px;

    .stats-content {
      display: flex;
      align-items: center;
      gap: 16px;

      .stats-icon {
        width: 48px;
        height: 48px;
        border-radius: 8px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 20px;

        &.folders {
          background: #e3f2fd;
          color: #1976d2;
        }

        &.recent {
          background: #f3e5f5;
          color: #7b1fa2;
        }

        &.storage {
          background: #e8f5e8;
          color: #388e3c;
        }
      }

      .stats-info {
        .stats-number {
          font-size: 24px;
          font-weight: 600;
          color: #303133;
          line-height: 1;
        }

        .stats-label {
          font-size: 12px;
          color: #909399;
          margin-top: 4px;
        }
      }
    }
  }
}

.filter-section {
  margin-bottom: 24px;

  .view-controls {
    display: flex;
    justify-content: flex-end;
  }
}

.folders-content {
  .empty-state {
    text-align: center;
    padding: 60px 20px;
  }

  .folder-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
    gap: 20px;

    .folder-card {
      position: relative;
      padding: 20px;
      border: 1px solid #ebeef5;
      border-radius: 12px;
      cursor: pointer;
      transition: all 0.3s;
      background: white;

      &:hover {
        border-color: #409eff;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.15);
        transform: translateY(-2px);

        .folder-actions {
          opacity: 1;
        }
      }

      .folder-icon {
        width: 60px;
        height: 60px;
        background: linear-gradient(135deg, #ffd54f, #ffb74d);
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 16px;
        color: white;
        font-size: 24px;
      }

      .folder-info {
        text-align: center;

        .folder-name {
          font-size: 16px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .folder-meta {
          .folder-date {
            font-size: 12px;
            color: #909399;
          }
        }
      }

      .folder-actions {
        position: absolute;
        top: 12px;
        right: 12px;
        opacity: 0;
        transition: opacity 0.3s;

        .action-btn {
          width: 28px;
          height: 28px;
          border-radius: 6px;
          background: rgba(255, 255, 255, 0.9);
          border: 1px solid #e4e7ed;

          &:hover {
            background: white;
            border-color: #409eff;
            color: #409eff;
          }
        }
      }
    }
  }

  .list-view {
    .folder-cell {
      display: flex;
      align-items: center;
      gap: 8px;

      .folder-icon-small {
        color: #ffa726;
        font-size: 16px;
      }

      .folder-name {
        font-weight: 500;
      }
    }
  }
}

@media (max-width: 768px) {
  .folder-management {
    padding: 15px;
  }

  .page-header .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;

    .header-actions {
      width: 100%;
      justify-content: center;
    }
  }

  .stats-section {
    .el-col {
      margin-bottom: 16px;
    }
  }

  .filter-section {
    .el-col {
      margin-bottom: 12px;
    }

    .view-controls {
      justify-content: center;
    }
  }

  .folder-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
  }
}
</style>
